package com.googlecode.maven.plugin.appassembler.launcher.program;

import com.googlecode.maven.plugin.appassembler.App;
import com.googlecode.maven.plugin.appassembler.ResourceUtils;
import com.googlecode.maven.plugin.appassembler.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.maven.plugin.MojoFailureException;

/**
 * Generates files for the program launcher.
 */
public class ProgramLauncher
    {
    /**
     * Resource prefix of template files.
     */
    private static final String RESOURCE_PREFIX = "classpath:/com/googlecode/maven/plugin/appassembler/launcher/program/";

    /**
     * Constructs a new ProgramLauncher object.
     */
    private ProgramLauncher()
        {
        super();
        }

    /**
     * Generate files for the program launcher.
     *
     * @param configuration Program launcher configuration.
     * @param app Application.
     * @param targetDirectory Target directory.
     * @throws MojoFailureException If this operation failed.
     */
    public static void apply(ProgramLauncherConfiguration configuration, App app,
            File targetDirectory)
            throws MojoFailureException
        {
        if ((app.getJavaParameters() != null) && !app.getJavaParameters().
                isEmpty())
            {
            if (configuration.getJavaParameters() == null)
                {
                configuration.setJavaParameters(new ArrayList<String>());
                }
            configuration.getJavaParameters().addAll(app.getJavaParameters());
            }

        String unixJavaCommand = configuration.getJavaCommand().replaceAll(
                "%(\\w+)%", "\\$$1");

        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("app", app);
        vars.put("configuration", configuration);
        vars.put("unixJavaCommand", unixJavaCommand);

        String path = String.format("bin/%s", app.getAppName());
        File targetFile = new File(targetDirectory, path);
        ResourceUtils.copyTemplateResource(
                RESOURCE_PREFIX + "bin/AppCommand.ftl", targetFile, vars);
        Utils.addExecutableFile(app, path, targetDirectory);

        path = String.format("bin/%s.bat", app.getAppName());
        targetFile = new File(targetDirectory, path);
        ResourceUtils.copyTemplateResource(
                RESOURCE_PREFIX + "bin/AppCommand.bat.ftl", targetFile, vars);
        }
    }
